const express = require("express");

// 创建app对象
const app = express();

app.use(express.json()); // 解析json格式的请求体

// 编写中间件
app.post("/login", (req, res, next) => {
  // 1. 获取登录传入的用户名和密码
  const { username, password } = req.body;
  console.log(username, password, req.body);

  // 2. 对用户名和密码进行判断
  if (!username || !password) {
    next(-1001);
  } else if (username !== "admin" || password !== "123456") {
    next(-1002);
  } else {
    res.json({
      code: 200,
      message: "登录成功",
      token: "1234567890fjlsdkjafl",
    });
  }
});

app.use((err, req, res, next) => {
  console.log(err, "错误");
  if (err === -1001) {
    res.json({
      code: -1001,
      message: "用户名或密码不能为空",
    });
  } else if (err === -1002) {
    res.json({
      code: -1002,
      message: "用户名或密码错误",
    });
  } else {
    res.json({
      code: 500,
      message: "服务器内部错误",
    });
  }
});

// 启动服务器
app.listen(9000, () => {
  console.log("express服务器启动成功~");
});
